//- Copyright (C) 2023 Beijing Huaxia Chunsong Technology Co., Ltd. 
//- <https://www.chatopera.com>, Licensed under the Chunsong Public 
//- License, Version 1.0  (the "License"), https://docs.cskefu.com/licenses/v1.html
//- Unless required by applicable law or agreed to in writing, software
//- distributed under the License is distributed on an "AS IS" BASIS,
//- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//- See the License for the specific language governing permissions and
//- limitations under the License.
//- Copyright (C) 2018-Jun. 2023 Chatopera Inc, <https://www.chatopera.com>
//- Licensed under the Apache License, Version 2.0
//- http://www.apache.org/licenses/LICENSE-2.0
.uk-layui-form
    form.layui-form.uk-form
        input(type='hidden', name='id', value=userData.id)
        .layui-form-item
            label.layui-form-label 用户名：
            .layui-input-inline
                input.layui-input(type='text', name='username', value=userData.username, required, lay-verify='required_username', placeholder='请输入用户名', autocomplete='off')
            .layui-form-mid.layui-word-aux 用户登录的账号
        .layui-form-item
            label.layui-form-label 姓名：
            .layui-input-inline
                input.layui-input(type='text', name='uname', value=userData.uname, required, lay-verify='required_name', placeholder='请输入用户姓名', autocomplete='off')
        .layui-form-item
            label.layui-form-label 电子邮件：
            .layui-input-inline
                input.layui-input(type='email', name='email', value=userData.email, placeholder='请输入电子邮件地址', autocomplete='off')
        .layui-form-item
            label.layui-form-label 密码：
            .layui-input-inline
                input#password.layui-input(type='password', name='password', placeholder='请输入登录密码', lay-verify='pass', autocomplete='off')
            .layui-form-mid.layui-word-aux(style='padding-bottom: 0px')
                input#repassword.layui-input(type='password', name='repassword', lay-verify='repass', placeholder='请再次输入密码', autocomplete='off', style='margin-top: 6px;')
        .layui-form-item
            label.layui-form-label 手机号：
            .layui-input-inline
                input.layui-input(type='mobile', name='mobile', value=userData.mobile, placeholder='请输入手机号码', autocomplete='off')
        .layui-form-item
            label.layui-form-label 管理员：
            .layui-input-inline
                input(type="checkbox" name="admin" lay-skin="switch" value="1" lay-filter="admincheckbox" lay-text="是|否" checked= userData.admin && "checked")
            .layui-form-mid.layui-word-aux(style='padding: 0 0; line-height: 20px') 管理员具备访问和修改所有系统资源的权限，同时也设定为多媒体坐席
        .layui-form-item#agentDiv
            .layui-form-item
                label.layui-form-label 多媒体坐席：
                .layui-input-inline
                    input(type="checkbox" name="agent" lay-skin="switch" value="1" lay-filter="agent" lay-text="开启|关闭" checked=userData && userData.agent == true && "checked")
        if models.contains("callcenter")
            //<div class="layui-form-item" id="callcenterDiv">
            //  <label class="layui-form-label">呼叫中心坐席：</label>
            //  <div class="layui-input-inline">
            //    <input type="checkbox" name="callcenter" lay-skin="switch"  value="1" lay-filter="callcenter" lay-text="开启|关闭">
              //   </div>
              //   <div class="layui-form-mid layui-word-aux" id="sipAccountDiv">
              //      <input type="text" id="sipAccount" name="sipaccount" lay-verify="sip"  placeholder="请输入SIP地址" autocomplete="off" class="layui-input">
            //  </div>
            //</div>
            #callcenter.layui-form-item
                label.layui-form-label 呼叫中心坐席：
                .layui-input-inline(style="margin-left:0px;")
                    input(type="checkbox", name="callcenter", lay-skin="switch", lay-filter="callcenter", value="1", lay-text="开启|关闭")
            #bindext_tip.layui-form-item
                label.layui-form-label 呼叫中心：
                .layui-input-inline
                    select#callcenterhostid(name="pbxhostid", lay-filter="hostid", lay-verify="callcenterhost")
                        option(value="") 请选择呼叫中心
                #extenttions.layui-form-mid(style="padding-top:5px !important;")
                    select#callcenterExtid(name="extensionid", lay-verify="callcenterext")
                        option(value="") 请选择分机
                            if userData && userData.callcenter == true && userData.extension
                                for extension in userData.extension
                                    if userData.extensionId
                                        option(
                                            value=extension.id
                                            selected=userData.extensionId && userData.extensionId == extension.id && "selected"
                                        )
                                            = extension.extension
                                    else
                                        option(value=extension.id)= extension.extension
        .layui-form-button
            .layui-button-block
                button.layui-btn(lay-submit, lay-filter='sys-user-update') 立即提交
script.
    layui.use('form', function () {
        var form = layui.form();
        form.render(); //更新全部
        form.verify({
            repass: function (value) {
                if (value != $('#password').val()) {
                    return '两次输入的密码不一致，请确认';
                }
            },
            sip: function (value) {
                if ($("input[name=callcenter]:checked").length > 0 && value === '') {
                    return 'SIP地址不能为空，请确认';
                }
            },
            required_username: function (value) {
                if (value.length > 50) {
                    return "用用户名不能超过50字";
                }
            },
            required_name: function (value) {
                if (value.length > 100) {
                    return "用户姓名不能超过100字";
                }
            },
            callcenterhost: function (value) {
                if ($("input[name=callcenter]:checked").length > 0 && value === '') {
                    return '呼叫中心不能为空，请确认';
                }
            },
            callcenterext: function (value) {
                if ($("input[name=callcenter]:checked").length > 0 && value === '') {
                    return '分机不能为空，请确认';
                }
            }
        });

        // if($("input[name=callcenter]:checked").length < 1){
        //     $('#callcenterDiv').hide();
        //     $('#sipAccountDiv').hide();
        // }

        // 当账号为管理员类型时，强制设定为坐席！
        form.on('switch(admincheckbox)', function (data) {
            if (data.elem.checked) {
                // 坐席的按钮
                if ($('#agentDiv > div > div > div > em').text() == "关闭") {
                    // 之前未开启
                    document.querySelector('#agentDiv > div > div > div > i').click();
                }
                // 设置为禁用
                $("#agentDiv > div > div > input[name=agent]").attr('disabled', 'disabled');
            } else {
                // 取消禁用
                $("#agentDiv > div > div > input[name=agent]").removeAttr('disabled');
            }
        });

        form.on('switch(callcenter)', function (data) {
            if (data.elem.checked) {
                $('#bindext_tip').show();
                restApiRequest({
                    silent: true,
                    path: 'callcenter',
                    data: {
                        ops: "my-pbxlist"
                    }
                }).then(function (result) {
                    if (result.rc == 0) {
                        if (result.data.length > 0) {
                            for (var i = 0; i < result.data.length; i++) {
                                $("#callcenterhostid").append('<option value="' + result.data[i].id + '">' + result.data[i].name + '</option>')
                            }
                            ;
                            form.render("select");
                        }
                    }
                }, function (err) {
                    handleRestApiFail(err);
                });
            } else {
                $('#bindext_tip').hide();
            }
        });

        form.on('select(hostid)', function (data) {
            restApiRequest({
                silent: true,
                path: 'callcenter',
                data: {
                    ops: "ext-dd-vacant",
                    id: data.value
                }
            }).then(function (result) {
                if (result.rc == 0) {
                    if (result.data.length > 0) {
                        for (var i = 0; i < result.data.length; i++) {
                            $("#callcenterExtid").append('<option value="' + result.data[i].id + '">' + result.data[i].extension + '</option>')
                        }
                        ;
                        form.render("select");
                    }
                }
            }, function (err) {
                handleRestApiFail(err);
            });
        });

        var callcenter = "${userData.callcenter!''}", pbxhostId = "${userData.pbxhostId!''}",
            extensionId = "${userData.extensionId!''}";
        if (callcenter == 'true') {
            restApiRequest({
                silent: true,
                path: 'callcenter',
                data: {
                    ops: "my-pbxlist"
                }
            }).then(function (result) {
                if (result.rc == 0) {
                    if (result.data.length > 0) {
                        for (var i = 0; i < result.data.length; i++) {
                            var Option = $('<option value="' + result.data[i].id + '">' + result.data[i].name + '</option>');
                            if (result.data[i].id = pbxhostId) {
                                $(Option).attr('selected', true)
                            }
                            $("#callcenterhostid").append(Option)
                        }
                        ;
                        form.render("select");
                    }
                }
            }, function (err) {
                handleRestApiFail(err);
            });

            restApiRequest({
                silent: true,
                path: 'callcenter',
                data: {
                    ops: "ext-dd-vacant",
                    id: pbxhostId
                }
            }).then(function (result) {
                if (result.rc == 0) {
                    if (result.data.length > 0) {
                        for (var i = 0; i < result.data.length; i++) {
                            $("#callcenterExtid").append('<option value="' + result.data[i].id + '">' + result.data[i].extension + '</option>')
                        }
                        ;
                        form.render("select");
                    }
                }
            }, function (err) {
                handleRestApiFail(err);
            });
        }

        // 根据“多媒体坐席”显示“呼叫中心坐席”状态
        // form.on('switch(agent)', function(data){
        //     $("input[name=callcenter]").prop("checked", false);
        //     form.render('checkbox','callcenter');
        // 	if(data.elem.checked){
        // 		$('#callcenterDiv').show();
        // 	}else{
        // 		$('#callcenterDiv').hide();
        // 	}
        //     $('#sipAccount').val("");
        //     $('#sipAccountDiv').hide();
        // });
        //
        // // 根据“多媒体坐席”显示“呼叫中心坐席”状态
        // form.on('switch(callcenter)', function(data){
        //     $('#sipAccount').val("");
        // 	if(data.elem.checked){
        // 		$('#sipAccountDiv').show();
        // 	}else{
        // 		$('#sipAccountDiv').hide();
        // 	}
        // });

        // 处理表单提交
        form.on('submit(sys-user-update)', function (data) {
            data.field['ops'] = 'update';
            restApiRequest({
                silent: true,
                path: 'user',
                data: data.field
            }).then(function (result) {
                if (result.rc == 0) {
                    processUserAddOrUpdateResult(result.data, function () {
                        $("span.layui-layer-setwin > a.layui-layer-close1").click();
                        // 关闭并刷新页面
                        document.getElementById("admin").contentWindow.location = '/admin/user/index.html';
                    });
                }
            }, function (err) {
                handleRestApiFail(err);
            });
            return false;
        });

    });

